<template>
  <div class="monitor-container">
    <!-- 上半部分：欢迎信息 -->
    <el-card class="welcome-section">
      <div class="welcome-content">
        <h1>欢迎使用</h1>
        <p>在这里您可以管理和监控微信用户的消息</p>
      </div>
    </el-card>

    <!-- 下半部分：用户列表 -->
    <el-card class="user-list-section">
      <template #header>
        <div class="card-header">
          <span>微信用户列表</span>
          <div class="header-buttons">
            <el-button type="primary" @click="refreshList">
              <el-icon><Refresh /></el-icon>
              刷新列表
            </el-button>
          </div>
        </div>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <!-- 空状态 -->
      <el-empty v-else-if="!userList.length" description="暂无微信用户" />

      <!-- 用户列表 -->
      <el-table v-else :data="userList" style="width: 100%">
        <el-table-column prop="nickname" label="微信昵称" min-width="120" />
        <el-table-column prop="device_id" label="微信ID" min-width="120" show-overflow-tooltip />
        <el-table-column prop="is_active" label="监控状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getMonitorStatusType(row.is_active)">
              {{ getMonitorStatusText(row.is_active) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="登录状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getOnlineStatusType(row.status)">
              {{ getOnlineStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="success" 
              link 
              :loading="row.operating"
              :disabled="row.is_active"
              @click="handleStartMonitor(row)"
            >
              开始监控
            </el-button>
            <el-button 
              type="danger" 
              link 
              :loading="row.operating"
              :disabled="!row.is_active"
              @click="handleStopMonitor(row)"
            >
              停止监控
            </el-button>
            <el-button
              type="primary"
              link
              :loading="row.waking"
              @click="refreshMonitorStatus(row)"
            >
              刷新监控状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElNotification } from 'element-plus'
import { messageStore } from '@/utils/messageStore'
import { socketService } from '@/utils/socket'

// 用户接口定义
interface WxUser {
  id: number
  nickname: string
  device_id: string
  status: number // 登录状态
  is_active: boolean // 监控状态
  auth_key: string
  operating?: boolean
  waking?: boolean // 刷新状态
}

const loading = ref(false)
const userList = ref<WxUser[]>([])
// const listenerRegistered = ref(false)
const joinedDeviceRooms = new Set<string>()



// 获取监控状态类型
const getMonitorStatusType = (status: boolean): '' | 'success' | 'warning' => {
  return status ? 'success' : 'warning'
}

// 获取监控状态文本
const getMonitorStatusText = (status: boolean): string => {
  return status ? '已监控' : '未监控'
}

// 获取在线状态类型
const getOnlineStatusType = (status: number): '' | 'success' | 'danger' => {
  return status === 1 ? 'success' : 'danger'
}

// 获取在线状态文本
const getOnlineStatusText = (status: number): string => {
  return status === 1 ? '在线' : '离线'
}

// 自动重新连接之前监控的设备
// const autoReconnectMonitoredDevices = async () => {
//   try {
//     // 从 localStorage 获取之前监控的设备列表
//     const monitoredDevices = JSON.parse(localStorage.getItem('monitoredDevices') || '[]')
//     if (monitoredDevices.length === 0) return
//
//     console.log('自动重新连接监控设备:', monitoredDevices)
//
//     // 连接 WebSocket
//     const socket = socketService.connect(localStorage.getItem('token') || undefined)
//
//     // 注册消息监听（只注册一次）
//     if (!listenerRegistered.value) {
//       socket.on('new_message', handleIncomingMessage)
//       listenerRegistered.value = true
//     }
//
//     // 重新加入之前监控的设备房间
//     for (const deviceId of monitoredDevices) {
//       if (!joinedDeviceRooms.has(deviceId)) {
//         socketService.joinRoom(deviceId)
//         joinedDeviceRooms.add(deviceId)
//         console.log('自动重新加入房间:', deviceId)
//       }
//     }
//   } catch (error) {
//     console.error('自动重新连接失败:', error)
//   }
// }

// 保存监控状态到 localStorage
const saveMonitoredDevices = () => {
  localStorage.setItem('monitoredDevices', JSON.stringify(Array.from(joinedDeviceRooms)))
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const response = await axios.get('/wx_users')
    if (response.data.code === 200) {
      userList.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取用户列表失败')
    }
  } catch (error: any) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  getUserList()
}

// 开始监控
const handleStartMonitor = async (user: WxUser) => {
  user.operating = true
  try {
    const response = await axios.post(`/rabbitmq/connect`,{"token_key":user.auth_key})
    if (response.data.code === 200) {

      // 加入该设备房间，room 即为 device_id（去重）
      if (!joinedDeviceRooms.has(user.device_id)) {
        socketService.joinRoom(user.device_id)
        joinedDeviceRooms.add(user.device_id)
        // 保存到 localStorage
        saveMonitoredDevices()
      }
      ElMessage.success('开始监控成功')
      // await getUserList()
      await refreshMonitorStatus( user)
    } else {
      ElMessage.error(response.data.msg || '开始监控失败')
    }
  } catch (error: any) {
    console.error('开始监控失败:', error)
    ElMessage.error('开始监控失败：' + (error.response?.data?.msg || error.message))
  } finally {
    user.operating = false
  }
}

// 停止监控
const handleStopMonitor = async (user: WxUser) => {
  user.operating = true
  try {
    const response = await axios.post(`/rabbitmq/disconnect`,{"token_key":user.auth_key})
    if (response.data.code === 200) {
      // 离开设备房间（去重）
      if (joinedDeviceRooms.has(user.device_id)) {
        socketService.leaveRoom(user.device_id)
        joinedDeviceRooms.delete(user.device_id)
        // 更新 localStorage
        saveMonitoredDevices()
      }
      ElMessage.success('停止监控成功')
      await refreshMonitorStatus( user)
      // await getUserList()
    } else {
      ElMessage.error(response.data.msg || '停止监控失败')
    }
  } catch (error: any) {
    console.error('停止监控失败:', error)
    ElMessage.error('停止监控失败：' + (error.response?.data?.msg || error.message))
  } finally {
    user.operating = false
  }
}

// 刷新监控状态
const refreshMonitorStatus = async (user: WxUser) => {
  user.waking = true
  try {
    const response = await axios.get(`/rabbitmq/refresh/${user.auth_key}`)
    if (response.data.code === 200) {
      // ElMessage.success('刷新监控状态成功')
      await getUserList()
    } else {
      ElMessage.error(response.data.msg || '刷新监控状态失败')
    }
  } catch (error: any) {
    console.error('刷新监控状态失败:', error)
    ElMessage.error('刷新监控状态失败：' + (error.response?.data?.msg || error.message))
  } finally {
    user.waking = false
  }
}
// 页面加载时获取用户列表
onMounted(async () => {
  // 再获取用户列表
  getUserList()
})
</script>

<style scoped lang="scss">
.monitor-container {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .welcome-section {
    .welcome-content {
      text-align: center;
      padding: 20px;

      h1 {
        font-size: 24px;
        color: #303133;
        margin-bottom: 16px;
      }

      p {
        font-size: 16px;
        color: #606266;
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .loading-container {
    padding: 20px 0;
  }
}
</style> 